#include "AsyncSender.h"

U2L::AsyncSender::AsyncSender(void)
{
	m_sending = false;
	m_disconnected = false;
	m_msg.clear();
	m_socket = NULL;
}

U2L::AsyncSender::~AsyncSender(void)
{
	this->Wait();
}

void U2L::AsyncSender::Send(sf::SocketTCP* _socket)
{
	if (_socket != NULL &&
		!m_sending &&
		!m_msg.empty())
	{
		m_socket = _socket;
		m_sending = true;
		m_disconnected = false;
		this->Launch();
	}
}

bool U2L::AsyncSender::IsSending(void) const
{
	return m_sending;
}

bool U2L::AsyncSender::IsDisconnected(void) const
{
	return m_disconnected;
}

void U2L::AsyncSender::SetMsg(std::wstring _msg)
{
	if (!m_sending)
	{
		m_msg = _msg;
	}
}

void U2L::AsyncSender::Run(void)
{
	try
	{
		sf::Packet packet;
		packet << m_msg;
		
		if (m_socket->Send(packet) != sf::Socket::Done)
		{
			m_disconnected = true;
		}
		m_msg.clear();
		m_socket = NULL;
		m_sending = false;
	}
	catch (std::exception& err)
	{
		std::cerr << err.what() << std::endl;
	}
}